import ButtonManager from './ButtonManager.js'; // 导入按钮管理模块

const BatchPriceCheck = {
  buttonId: 'batchPriceCheck', // 按钮 ID
  defaultText: '2. 批量核价', // 默认按钮文本

  // 初始化函数
  init() {
    document.getElementById(this.buttonId).addEventListener('click', this.handleClick.bind(this)); // 绑定点击事件
  },

  // 点击事件处理函数
  async handleClick() {
    ButtonManager.updateButtonState(this.buttonId, '2. 批量核价-处理中...', true); // 更新按钮状态为加载中
    ButtonManager.disableAllButtons(this.buttonId); // 禁用其他按钮

    try {
      const minimumNuclearPrices = Number(minimumNuclearPriceInput.value.trim());
      const minimumNuclearPrice = Math.floor(minimumNuclearPrices*100)
      
      console.log('minimumNuclearPrice',minimumNuclearPrice)
      if(isNaN(minimumNuclearPrice)){
        alert('请输入的核价最低价格')
        return
      }

      if (minimumNuclearPrice && minimumNuclearPrice>=6900) {
        console.log("输入的核价最低价格:",typeof minimumNuclearPrice, minimumNuclearPrice);
        // 这里可以添加更多的逻辑，比如将核价最低价格存储到 localStorage 或者发送到后台脚本
      }else {
        alert('请输入的核价最低价格/不能低于69')
        console.log('请输入的核价最低价格/不能低于6900')
        return
      }

      const { mallId, antiContent } = await new Promise((resolve) => {
        chrome.storage.local.get(['mallId', 'antiContent'], resolve); // 从本地存储获取 mallId 和 antiContent
      });

      if (!mallId || !antiContent) {
        console.error("mallId 或 antiContent 未找到"); // 检查是否获取到必要参数
        return;
      }

      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); // 获取当前标签页

      const results = await chrome.scripting.executeScript({
        target: { tabId: tab.id }, // 注入脚本到当前标签页
        func: executePriceReview, // 执行核价逻辑
        args: [mallId, antiContent,minimumNuclearPrice], // 传递参数
      });

      if (results && results[0] && results[0].result) {
        console.log("获取核价数据完成，返回数据:", results[0].result); // 输出核价结果
        alert("获取核价数据完成，返回数据:", results[0].result)
        location.reload()
      } else {
        console.error("未获取到有效数据"); // 输出错误信息
      }
    } catch (error) {
      console.error("获取核价数据失败:", error); // 捕获错误
    } finally {
      ButtonManager.resetButtonState(this.buttonId, this.defaultText); // 恢复按钮状态
      ButtonManager.enableAllButtons(); // 启用所有按钮
    }
  },
};

// 核价逻辑函数
function executePriceReview(j_mallid, j_anti_content,j_smallPrice = 6900) {
  console.log(j_smallPrice)
  return new Promise((resolve, reject) => {
    console.log("开始执行核价逻辑...");
    console.log("接收到的参数:", { j_mallid, j_anti_content });

    let j_pageNum = 1; // 页码
    let j_pagesNum = 1; // 总页码
    let j_total = 1; // 未核价总数量
    let j_pageSize = 100; // 一页多少条数据
    let j_body = {
      pageSize: j_pageSize,
      pageNum: j_pageNum,
      priceReviewStatusList: [0, 1, 2, 3],
      secondarySelectStatusList: [7],
      supplierTodoTypeList: [1]
    };

    let j_orderIdsArr = []; // 查询核价id数组
    // let j_smallPrice = 6900; // 最低核价价格
    let j_totall = 0; // 累计核价数量

    // 获取核价数据
    function j_searchForSemiSupplier() {
      j_body.pageNum = j_pageNum;
      fetch("https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/xmen/select/searchForSemiSupplier", {
        method: 'POST',
        headers: {
          accept: '*/*',
          'accept-language': 'zh-CN,zh;q=0.9',
          'anti-content': j_anti_content,
          'cache-control': 'max-age=0',
          'content-type': 'application/json',
          mallid: j_mallid,
          priority: 'u=1, i',
          'sec-ch-ua': '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"macOS"',
          'sec-fetch-dest': 'empty',
          'sec-fetch-mode': 'cors',
          'sec-fetch-site': 'same-origin'
        },
        referrer: 'https://seller.kuajingmaihuo.com/main/product/seller-select',
        referrerPolicy: 'strict-origin-when-cross-origin',
        body: JSON.stringify(j_body),
        mode: 'cors',
        credentials: 'include'
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          if (data.success) {
            console.log(data.result.dataList);
            j_total = data.result.total;
            j_pagesNum = Math.ceil(j_total / j_pageSize);
            j_pageNum++;

            let dataList = data.result.dataList;
            let newArr = [];
            dataList.forEach((item, index) => {
              item.skcList.forEach((itemSub, indexSub) => {
                itemSub.supplierPriceReviewInfoList.forEach((itemSubs, indexSubs) => {
                  j_orderIdsArr.push(itemSubs.priceOrderId);
                });
              });
            });
            console.log('查询价格参数', j_orderIdsArr);

            if (j_orderIdsArr.length > 0) {
              j_query({ orderIds: j_orderIdsArr });
            } else {
              if (j_pageNum <= j_pagesNum) {
                j_searchForSemiSupplier();
              } else {
                console.log('数据加载完成');
                resolve('数据加载完成');
              }
            }
          } else {
            if (j_pageNum <= j_pagesNum) {
              j_searchForSemiSupplier();
            } else {
              console.log('数据加载完成');
              resolve('数据加载完成');
            }
          }
        })
        .catch(error => {
          console.error('There was a problem with your fetch operation:', error);
          reject(error);
        });
    }

    // 查询核价数据价格
    function j_query(orderIds) {
      fetch("https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/magnus/price/bargain-no-bom/batch/info/query", {
        method: 'POST',
        headers: {
          accept: '*/*',
          'accept-language': 'zh-CN,zh;q=0.9',
          'anti-content': j_anti_content,
          'cache-control': 'max-age=0',
          'content-type': 'application/json',
          mallid: j_mallid,
          priority: 'u=1, i',
          'sec-ch-ua': '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"macOS"',
          'sec-fetch-dest': 'empty',
          'sec-fetch-mode': 'cors',
          'sec-fetch-site': 'same-origin'
        },
        referrer: 'https://seller.kuajingmaihuo.com/main/product/seller-select',
        referrerPolicy: 'strict-origin-when-cross-origin',
        body: JSON.stringify(orderIds),
        mode: 'cors',
        credentials: 'include'
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          console.log('查询价格结果');
          if (data.success) {
            console.log(data);
            let priceReviewItemList = data.result.priceReviewItemList;
            let itemRequests = [];
            priceReviewItemList.forEach((item, index) => {
              let itemsArr = [];
              let obj = {
                priceOrderId: item.id,
                supplierResult: 3,
                items: []
              };
              if (j_smallPrice <= item.suggestSupplyPrice) {
                item.skuInfoList.forEach((itemSub, indexSub) => {
                  itemsArr.push({ productSkuId: itemSub.productSkuId, price: itemSub.suggestSupplyPrice });
                });
                obj.supplierResult = 1;
              } else {
                // 重新核价
                item.skuInfoList.forEach((itemSub, indexSub) => {
                  itemsArr.push({ productSkuId: itemSub.productSkuId, price: 8800 });
                });
                obj.supplierResult = 2;

              }
              obj.items = itemsArr;
              itemRequests.push(obj);
            });
            console.log('提交核价的数据', itemRequests);
            if (itemRequests.length > 0) {
              j_batch(itemRequests);
            } else {
              console.warn('没有查询到价格待确认的数据');
              resolve('没有查询到价格待确认的数据');
            }
          } else {
            console.log('查询价格错误', orderIds);
            reject('查询价格错误');
          }
        })
        .catch(error => {
          console.error('There was a problem with your fetch operation:', error);
          reject(error);
        });
    }

    // 提交核价
    let j_batchNum = 0;
    function j_batch(arr) {
      let j_batchbody = {
        itemRequests: arr
      };
      console.log(arr);
      fetch("https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/magnus/price/bargain-no-bom/batch", {
        method: 'POST',
        headers: {
          accept: '*/*',
          'accept-language': 'zh-CN,zh;q=0.9',
          'anti-content': j_anti_content,
          'cache-control': 'max-age=0',
          'content-type': 'application/json',
          mallid: j_mallid,
          priority: 'u=1, i',
          'sec-ch-ua': '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"macOS"',
          'sec-fetch-dest': 'empty',
          'sec-fetch-mode': 'cors',
          'sec-fetch-site': 'same-origin'
        },
        referrer: 'https://seller.kuajingmaihuo.com/main/product/seller-select',
        referrerPolicy: 'strict-origin-when-cross-origin',
        body: JSON.stringify(j_batchbody),
        mode: 'cors',
        credentials: 'include'
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          console.log(data.success ? '核价成功' : ('核价失败，' + data.errorMsg));
          if (data.success) {
            j_totall += arr.length;
            console.log('核价成功:' + arr.length, '累计核价成功数量:' + j_totall);
            j_searchForSemiSupplier();
          } else {
            console.log('核价失败,' + data.errorMsg);
            if (j_batchNum < 5) {
              j_batchNum++;
              j_batch(arr);
            } else {
              console.log('失败核价超过5次，稍后再试试');
              j_batchNum = 0;
              reject('失败核价超过5次，稍后再试试');
            }
          }
        })
        .catch(error => {
          console.error('There was a problem with your fetch operation:', error);
          reject(error);
        });
    }

    // 开始执行核价逻辑
    j_searchForSemiSupplier();
  });
}

export default BatchPriceCheck; // 导出模块